package pv3d.cameras
{
	import core.MainManager;
	
	import flash.events.MouseEvent;
	
	import memory.MemoryRecovery;
	
	import org.papervision3d.cameras.Camera3D;
	/**
	 * 镜头一直对准中心点，随着鼠标拖动而变化位置
	 */ 
	public class RotateableTargetCamera extends Camera3D
	{
		public var radius:Number=1000;                                                                      //镜头旋转的半径
		private var sourceX:Number,sourceY:Number,sourceCameraRotationX:Number,sourceCameraRotationY:Number;//点击鼠标的时候，镜头的初始坐标和初始角度
		public function RotateableTargetCamera(focus:Number=25, zoom:Number=3)
		{
			super();
			this.z=-1000;
			init();
		}
		private function init():void
		{
			MainManager.getInstance().stage.addEventListener(MouseEvent.MOUSE_DOWN,on_mouse_down);
			MainManager.getInstance().stage.addEventListener(MouseEvent.MOUSE_UP,on_mouse_up);
		}
		//鼠标按下去的时候，存储镜头的属性，添加镜头移动的事件
		private function on_mouse_down(e:MouseEvent):void
		{
			sourceX=MainManager.getInstance().stage.mouseX;
			sourceY=MainManager.getInstance().stage.mouseY;
			sourceCameraRotationX=this.rotationX;
			sourceCameraRotationY=this.rotationY;
			MainManager.getInstance().stage.addEventListener(MouseEvent.MOUSE_MOVE,on_mouse_move);
		}
		//鼠标起来的时候，清除移动的事件
		private function on_mouse_up(e:MouseEvent):void
		{
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_move);
		}
		//鼠标离开的时候，清除移动的事件
		private function on_mouse_out(e:MouseEvent):void
		{
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_move);
		}
		//鼠标拖动的时候，不断更新镜头的位置和角度
		private function on_mouse_move(e:MouseEvent):void
		{
			this.rotationX=sourceCameraRotationX+-(sourceY-MainManager.getInstance().stage.mouseY)*0.3;
			this.rotationY=sourceCameraRotationY+-(sourceX-MainManager.getInstance().stage.mouseX)*0.3;
			var angleX:Number=(Math.PI * 2)*this.rotationX/360;
			var angleY:Number=(Math.PI * 2)*this.rotationY/360;
			this.z=-radius*Math.cos(angleY)*Math.cos(angleX);
			this.y=radius*Math.sin(angleX);
			this.x=-radius*Math.sin(angleY)*Math.cos(angleX);
		}
		public override function dispose():void
		{
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_move);
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_down);
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_up);
			MemoryRecovery.getInstance().gcFun(MainManager.getInstance().stage,MouseEvent.MOUSE_MOVE,on_mouse_out);
			super.dispose();
		}
	}
}